<template>
  <div id="memberManage">
    <div class="memberManage-top">
      <Form
        :model="userGroupData"
        ref="editForm"
        slot="search-bar"
        class="ivu-form-no-margin-bottom"
        :label-width="82"
        inline
      >
        <Form-item prop="code" :label="$t('module.general.groupCode')">
          <Input disabled v-model="userGroupData.groupCode" />
        </Form-item>
        <Form-item prop="name" :label="$t('module.general.groupName')">
          <Input disabled v-model="userGroupData.groupName" />
        </Form-item>
      </Form>
    </div>
    <!-- <div class="divid-line"></div> -->

    <div class="memberManage-title">
        <h4>{{ $t("module.general.AssignUsers") }}</h4>
    </div>
    <div class="transfer-content">
      <!-- 左侧区域 -->
      <div class="transfer-left tansDiv">
        <div class="left-content">
          <!-- 搜索区域 -->
          <SelfAdaption>
            <Form
              :model="conditionLeft"
              ref="transferLeftListForm"
              slot="adaption-bar"
              label-position="top"
              class="ivu-form-no-margin-bottom"
              inline
              :label-width="0"
              @submit.native.prevent
            >
              <Form-item prop="userName">
                <Input
                  icon="ios-search"
                  :placeholder="$t('module.general.tip.enterUser')"
                  @on-change="searchHandler('left')"
                  v-model="conditionLeft.userName"
                />
              </Form-item>
            </Form>
          </SelfAdaption>
          <InnerPageTable ref="transferLeftListTable" :config="configLeft"></InnerPageTable>
        </div>
      </div>

      <!-- 添加用户、移除用户 中间穿梭按钮 -->
      <div class="transfer-center tansDiv">
        <div>
          <div class="addUserBtn" @click="addSelectUsersBtn">
            {{ $t("module.general.addUser") }}
            <span>&gt;&gt;</span>
          </div>
          <div class="deleUserBtn" @click="deletSelectUsersBtn">
            <span>&lt;&lt;</span>
            {{ $t("module.general.delUser") }}
          </div>
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="transfer-right tansDiv">
        <div class="right-content">
          <!-- 搜索区域 -->
          <SelfAdaption>
            <Form
              :model="conditionRight"
              ref="transferLeftRightForm"
              slot="adaption-bar"
              label-position="top"
              class="ivu-form-no-margin-bottom"
              inline
              :label-width="0"
              @submit.native.prevent
            >
              <Form-item prop="userName">
                <Input
                  icon="ios-search"
                  :placeholder="$t('module.general.tip.enterUser')"
                  @on-change="searchHandler('right')"
                  v-model="conditionRight.userName"
                />
              </Form-item>
            </Form>
          </SelfAdaption>
          <InnerPageTable ref="transferRightListTable" :config="configRight"></InnerPageTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import locales from "./locales.js";
import {
  findGroupPersonList,
  findOtherPersonList,
  delGroupPersonList,
  addGroupPersonList
} from "@/api/userGroupApi";
import { GroupPersonLeft, GroupPersonRight } from "./coulmns";
import { queryOrgsByOrgPaths } from "@/api/orgApi";

export default {
  name: "GroupPersonManage",
  mixins: [locales],
  props: {
    row: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      fun: null,
      userGroupData: {},
      conditionLeft: {
        userName: "",
        tenantId: "",
        groupId: ""
      },
      conditionRight: {
        groupId: "",
        groupName: "",
        tenantId: "",
        userName: ""
      },
      tableSelectionLeft: [],
      tableSelectionRight: []
    };
  },
  computed: {
    configLeft() {
      const condition = this.conditionLeft;
      return {
        loadDataFn: this.queryUnassignedList,
        columnsFn: GroupPersonLeft.bind(this),
        onSelectionChange: this.pageTableSelectionLeft,
        initParam: { condition }
      };
    },
    configRight() {
      const condition = this.conditionRight;
      return {
        loadDataFn: this.queryAssignedList,
        columnsFn: GroupPersonRight.bind(this),
        onSelectionChange: this.pageTableSelectionRight,
        initParam: { condition },
        rowClassNameFn: this.rowClassName // 自定义行样式
      };
    }
  },
  methods: {
    // 自定义行样式
    rowClassName(row) {
      if (row.locked == 1) {
        return "tableDisableStyle";
      }
    },
    initRequest() {
      if (this.row.id) {
        this.userGroupData = this.row;
        this.conditionRight.groupId = this.row.id;
        this.conditionLeft.groupId = this.row.id;
        this.searchHandler();
      } else {
        console.log("用户组不存在");
      }
    },
    pageTableSelectionLeft(tableVal) {
      this.tableSelectionLeft = [];
      const groupId = this.userGroupData.id;
      tableVal.forEach(item => {
        this.tableSelectionLeft.push({
          groupId: groupId,
          userId: item.id
        });
      });
    },
    pageTableSelectionRight(tableVal) {
      this.tableSelectionRight = [];
      tableVal.forEach(item => {
        this.tableSelectionRight.push(item.id);
      });
    },
    // 删除用户
    userDeleted(id) {
      new $confirm(this.$t("common.warning.confirmToRemove"), this).then(() => {
        delGroupPersonList(id)
          .then(() => {
            this.$message.success({
              content: this.$t("common.deleteSuccess"),
              duration: 3
            });
            this.tableSelectionRight = [];
            this.searchHandler();
          })
          .catch(err => {
            console.log(err);
            this.$message.error({
              content: this.$t("common.deleteFailed"),
              duration: 3
            });
          });
      });
    },
    // 添加用户
    addUsers(id) {
      addGroupPersonList(id)
        .then(() => {
          this.$message.success({
            content: this.$t("common.addSuccess"),
            duration: 3
          });
          this.tableSelectionLeft = [];
          this.searchHandler();
        })
        .catch(err => {
          console.log(err);
          this.$message.error({
            content: this.$t("common.addFailed"),
            duration: 3
          });
        });
    },
    //   防抖函数
    debounce(fn, wait = 1000) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    add() {
      if (this.tableSelectionLeft.length > 0) {
        // const addData = self.tableSelectionLeft.join(',');
        this.addUsers(this.tableSelectionLeft);
      } else {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
      }
    },
    addSelectUsersBtn() {
      this.debounce(this.add, 300);
    },
    // 批量删除
    deletSelectUsersBtn() {
      if (this.tableSelectionRight.length > 0) {
        // const deleteData = self.tableSelectionRight.join(',');
        this.userDeleted(this.tableSelectionRight);
      } else {
        this.$message.error({
          content: this.$t("common.warning.selctElement"),
          duration: 3
        });
      }
    },
    // 单个删除
    singleDelete(id) {
      this.tableSelectionRight = [];
      this.tableSelectionRight.push(id);
      this.userDeleted(this.tableSelectionRight);
    },
    // 搜索table
    searchHandler(searchTable) {
      this.$nextTick(() => {
        if (searchTable === "left") {
          this.$refs["transferLeftListTable"].load(this.conditionLeft, 1);
        } else if (searchTable === "right") {
          this.$refs["transferRightListTable"].load(this.conditionRight, 1);
        } else {
          this.$refs["transferLeftListTable"].load(this.conditionLeft, 1);
          this.$refs["transferRightListTable"].load(this.conditionRight, 1);
        }
      });
    },
    queryUnassignedList: tableObj => {
      let { responseProcess, param, initParam } = tableObj;
      const _param = Object.assign({}, param, initParam);
      findOtherPersonList(_param).then(data => {
        let orgPaths = data.records.map(user => {
          return user.orgPath;
        });

        queryOrgsByOrgPaths(orgPaths).then(orgs => {
          data.records.forEach(user => {
            let userOrg = orgs.find(org => {
              return org.orgPath == user.orgPath;
            });
            user._hasOrgInfo = true;
            if (userOrg) {
              user.orgName = userOrg.orgName;
              user.orgNameFullPath = userOrg.orgNameFullPath;
            } else {
              user.orgName = user.orgPath;
              user.orgNameFullPath = user.orgPath;
            }
          });
          tableObj.tableData = data.records;
        });
        responseProcess(data);
      });
    },
    queryAssignedList: tableObj => {
      let { responseProcess, param, initParam } = tableObj;
      const _param = Object.assign({}, param, initParam);

      findGroupPersonList(param).then(data => {
        let orgPaths = data.records.map(user => {
          return user.orgPath;
        });

        queryOrgsByOrgPaths(orgPaths).then(orgs => {
          data.records.forEach(user => {
            let userOrg = orgs.find(org => {
              return org.orgPath == user.orgPath;
            });
            user._hasOrgInfo = true;
            if (userOrg) {
              user.orgName = userOrg.orgName;
              user.orgNameFullPath = userOrg.orgNameFullPath;
            } else {
              user.orgName = user.orgPath;
              user.orgNameFullPath = user.orgPath;
            }
          });
          tableObj.tableData = data.records;
        });

        responseProcess(data);
      });
    }
  },
  created() {
    // this.initRequest();
  },
  mounted() {
    this.initRequest();
  }
};
</script>

<style lang="less">
#memberManage {
  .memberManage-top {
    padding: 16px 10px 0;
  }
  .transfer-content {
    width: 100%;
    padding: 16px 10px;
  }
  .memberManage-title {
    width: 100%;
    border-bottom: 1px solid rgb(224, 221, 221);
    padding: 10px;
    padding-top: 0;
    h4 {
      height: 20px;
      line-height: 20px;
    }
  }
  .transfer-content {
    display: flex;
    .tansDiv {
      .single-table-con {
        padding: 0;
      }
      .run-search-bar div {
        margin: 0;
        width: 100%;
      }
      .ivu-form-inline {
        padding: 0;
        min-height: 0;
      }
      .ivu-form-inline .ivu-form-item {
        margin: 0;
      }
      .ivu-form-inline .ivu-input-wrapper {
        width: 100%;
      }
      .ivu-input {
        border-radius: 3px;
      }
      .inner-table {
        padding: 5px 10px 20px 5px;
        min-height: 500px;
        border-radius: 5px;
      }
      .self-adaption-wrap {
        margin-top: 10px;
      }
      .table-bar {
        margin: 0 0 10px;
      }
    }
    .transfer-left {
      flex: 1;
      overflow-x: auto;
      .left-content {
        border: 1px solid rgb(224, 221, 221);
        border-radius: 5px;
      }
    }
    .transfer-center {
      width: 126px;
      display: flex;
      justify-content: center;
      align-items: center;
      .addUserBtn {
        margin-bottom: 20px;
        background: #ff6f4b;
        border: 1px solid #ff6f4b;
        color: white;
      }
      .deleUserBtn {
        color: #ff6f4b;
        border: 1px solid #ff6f4b;
      }
      .addUserBtn,
      .deleUserBtn {
        min-height: 25px;
        line-height: 25px;
        padding: 0 10px;
        text-align: center;
        cursor: pointer;
        user-select: none;
      }
    }
    .transfer-right {
      flex: 1;
      overflow-x: auto;
      .right-content {
        border: 1px solid rgb(224, 221, 221);
        border-radius: 5px;
      }
    }
  }
  .ivu-spin {
    text-align: left;
  }
  .spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
}
</style>
